<template>
  <div style="">
    <Header :left="true" leftText="返回" title="临时用工-填报界面"> </Header>
    <div class="textScroll">
      <Form :style="autoHeight">
        <van-field
          label="部门名称"
          :value="companyname"
          readonly
          class="formstyle"
        />

        <van-cell
          title="日期选择"
          class="formstyle"
          required
          placeholder="请选择日期"
          is-link
          :value="form.planworkdatetime"
          @click="showdate = true"
        />
        <van-calendar
          :min-date="minDate"
          color="#1989fa"
          v-model="showdate"
          @confirm="onConfirm"
        />
        <van-field
          required
          readonly
          label="班次选择"
          placeholder=""
          class="formstyle"
        />
        <van-radio-group
          title="班次选择"
          v-model="form.pshiftid"
          direction="horizontal"
        >
          <van-radio name="1" checked-color="#138087" class="radioteam"
            >白班</van-radio
          >
          <van-radio name="2" checked-color="#138087" class="radioteam"
            >夜班</van-radio
          >
          <van-radio name="3" checked-color="#138087" class="radioteam"
            >中班</van-radio
          >
          <van-radio name="4" checked-color="#138087" class="radioteam"
            >转班(白)</van-radio
          >
          <van-radio name="5" checked-color="#138087" class="radioteam"
            >转班(夜)</van-radio
          >
        </van-radio-group>
        <van-field required readonly label="临时用工人数" class="formstyle" />
        <van-stepper class="radioteam" v-model="form.factworksused" step="1" />
        <van-field
          v-model="form.workhour"
          type="number"
          label="临时用工工时"
          placeholder="请输入工时"
          class="formstyle"
        />
        <van-field
          readonly
          is-link
          clickable
          label="用工类型"
          class="formstyle"
          :value="form.workertype"
          placeholder="选择用工类型"
          @click="showPicker1 = true"
        />
        <van-popup v-model="showPicker1" position="bottom">
          <van-picker
            show-toolbar
            :columns="employeetype"
            @cancel="showPicker1 = false"
            @confirm="onConfirmemployeetype"
          />
        </van-popup>

        <NoticeBar color="#1989fa" background="#ecf9ff" left-icon="video"
          >电子明细</NoticeBar
        >
        <Field
          :readonly="true"
          name="checkres"
          size="large"
          class="formstyle"
          @click="showCamera"
          label="资料上传"
          placeholder="————点击拍照————"
          right-icon="assets/right.png"
        />
        <div
          v-if="this.form.picList !== undefined && this.form.picList.length > 0"
        >
          <div
            style="margin-left: 15px"
            v-for="(imgUrl, ks) in this.form.picList"
            :key="ks"
          >
            <div class="van-uploader__wrapper" style="float: left">
              <div class="van-uploader__preview">
                <div
                  @click="picShow(ks)"
                  class="van-image van-uploader__preview-image"
                >
                  <img :src="imgUrl" class="van-image__img" />
                </div>
                <div
                  class="van-uploader__preview-delete"
                  @click="delObj('pic', imgUrl)"
                >
                  <i
                    class="van-icon van-icon-cross van-uploader__preview-delete-icon"
                  ></i>
                </div>
              </div>
            </div>
          </div>
        </div>
      </Form>

      <Button
        color="#f58220"
        :block="true"
        class="buttonLeft"
        v-show="btnShow"
        type="primary"
        text="取消"
        @click="close"
      />
      <Button
        color="#138087"
        :block="true"
        class="buttonRight"
        v-show="btnShow"
        :hairline="false"
        type="primary"
        text="保存"
        @click="saveform"
      />
    </div>
  </div>
</template>

<script>
import {
  Form,
  Cell,
  Icon,
  Field,
  NumberKeyboard,
  Image as VanImage,
  Picker,
  popup,
  SubmitBar,
  Button,
  Loading,
  Overlay,
  Dialog,
  Toast,
  NoticeBar,
  Row,
  Tag,
  DatetimePicker,
  ImagePreview,
  CellGroup,
  Uploader,
  Col,
  Cascader,
  Calendar,
  RadioGroup,
  Radio,
  Divider,
  Stepper,
} from "vant";

import "vue-easytable/libs/themes-base/index.css";
import { VTable } from "vue-easytable";
import { _httpClient } from "@/libs/api";
import { getToken, getBaseApiFrefix } from "@/libs/auth";
import Header from "@/components/header.vue";
import { storage } from "@/libs/utils";

Vue.use(Field);
Vue.use(Overlay);
Vue.use(Loading);
Vue.use(Picker);
Vue.use(popup);
Vue.use(SubmitBar);
Vue.use(VanImage);
Vue.use(DatetimePicker);
Vue.use(Cascader);
Vue.use(Calendar);
Vue.use(Cell);
Vue.use(RadioGroup);
Vue.use(Radio);
Vue.use(Divider);
Vue.use(Stepper);
Vue.use(ImagePreview);

export default {
  name: "temporarywork",
  components: {
    Button,
    Header,
    Form,
    Cell,
    Icon,
    Field,
    NumberKeyboard,
    VTable,
    Dialog,
    Toast,
    NoticeBar,
    Row,
    Tag,
    popup,
    DatetimePicker,
    ImagePreview,
    CellGroup,
    Uploader,
    Col,
    Calendar,
    Cascader,
    Picker,
    RadioGroup,
    Radio,
    Divider,
    Stepper,
  },
  data: function () {
    return {
      minDate: new Date(2021, 12, 1),
      companyname: "",
      employeetypevalue: "",
      employeetype: [
        "返工挑选",
        "设备临时损坏或停机",
        "临时性清洁工作",
        "临时离厂",
        "试模打样",
        "在线巡检",
      ],
      showPicker1: false,
      faualemployeetimenumber: "",
      faualemployeenumber: 1,
      radioteam: "1",
      btnShow: true,
      subButton: true, //提交按钮默认状态
      date: "",
      showdate: false,
      show: false,
      cascaderValue: "",
      form: {
        companyid: "", //公司代码
        planworkdatetime: "", //操作时间
        workertype: "", //用工类型
        workhour: 0, //用工工时
        factworksused: 1, //实际用工人数
        pshiftid: "1", //班次
        checked: 0, //审核状态
        creator: "",
        picList: [],
      },
    };
  },
  //页面初始化监听事件
  created: function () {
    this.user = JSON.parse(storage.get("user"));
    var myDate = new Date();
    this.form.planworkdatetime =
      myDate.getFullYear() +
      "-" +
      (myDate.getMonth() + 1) +
      "-" +
      myDate.getDate();
    //获取部门明细
    this.form.creator = this.user.userId;
    this.form.checktor = this.user.userId;
    this.companyname = this.user.dept.deptName;
    this.form.companyid = this.user.dept.deptId;
  },
  //页面初始化完成监听事件
  mounted: function () {
    const oldHight = api.winHeight;
    addEventListener("resize", () => {
      let newHight = api.winHeight;
      this.btnShow = newHight < oldHight ? false : true;
    });
  },
  methods: {
    onConfirmemployeetype(value) {
      this.form.workertype = value;
      this.showPicker1 = false;
    },
    onFinish({ selectedOptions }) {
      this.show = false;
      this.form.companyid = selectedOptions
        .map((option) => option.text)
        .join("/");
    },
    formatDate(date) {
      return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
    },
    onConfirm(date) {
      this.showdate = false;
      this.form.planworkdatetime = this.formatDate(date);
    },
    picShow(pIndex) {
      ImagePreview({
        images: this.form.picList || [],
        showIndicators: true,
        //startPosition: pIndex || 0,
        showIndex: false,
      });
    },
    showCamera() {
      let that = this;
      //alert("手机系统"+api.deviceName.toLowerCase());
      //判断设备系统类型
      if (api.systemType == "ios") {
        that.iosCamera();
      } else {
        var phoneInfo = api.require("phoneInfo");
        phoneInfo.getBaseInfo(function (ret, err) {
          if (ret.status) {
            if (ret.brand == "vivo") {
              // that.vivoCamera()
              that.iosCamera();
            } else if (ret.brand == "oppo") {
              that.oppoReno2Camera();
            } else if (ret.brand == "oneplus") {
              that.oppoReno2Camera();
            } else if (ret.brand == "honor") {
              that.vivoCamera();
            } else if (ret.brand == "xiaomi") {
              that.vivoCamera();
            } else if (ret.brand == "meizu") {
              that.vivoCamera();
            } else if (ret.brand == "realme") {
              that.vivoCamera();
            } else if (ret.brand == "huawei") {
              // that.vivoCamera();
              // that.otherCamera();
              that.otherCameraPlus();
            } else if (ret.brand == "ptac") {
              that.vivoCamera();
            } else {
              that.otherCameraPlus();
              // that.otherCamera();
            }
          } else {
            api.alert({ msg: err.msg });
          }
        });
      }
    },
    xiaomiCamera() {
      let that = this;
      var cameraTool = api.require("cameraTool");
      cameraTool.openCamera(function (ret, err) {
        let imgPath = ret.imgPath;
        if (imgPath && imgPath != "") {
          that.imageFilter(imgPath);
        }
      });
    },
    vivoCamera() {
      let that = this;
      var FNPhotograph = api.require("FNPhotograph");
      FNPhotograph.open(
        {
          album: false,
          quality: "high",
          isShowAlbum: false,
          // useAdvanceFeature: true,
          // pictureSize: '2075x1080',
          // previewSize: '2075x1080',
        },
        function (ret) {
          if (ret && ret.eventType == "takePhoto") {
            let imgSrc = ret.imagePath;
            if (imgSrc && imgSrc != "") {
              FNPhotograph.close();
              that.imageFilter(imgSrc);
            }
          }
        }
      );
    },
    oppoReno2Camera() {
      let _this = this;
      api.getPicture(
        {
          sourceType: "camera",
          encodingType: "jpg",
          mediaValue: "pic",
          allowEdit: false,
          destinationType: "url",
          quality: 50,
        },
        function (ret, err) {
          // 获取拍照数据并处理
          if (ret) {
            let imgSrc = ret.data;
            if (imgSrc && imgSrc != "") {
              _this.imageFilter(imgSrc);
            }
          }
        }
      );
    },
    otherCamera() {
      let that = this;
      // var cameraTool = api.require("cameraTool");
      // cameraTool.openCamera(function (ret, err) {
      //   let imgPath = ret.imgPath;
      //   if (imgPath && imgPath != "") {
      //     that.imageFilter(imgPath);
      //   }
      // });
      var module = api.require("easyCamera");
      var param = {
        typeString: "image", // 或者'video-20'
      };
      var resultCallback = function (ret, err) {
        var msg = ret.msg;
        if (msg && msg != "") {
          that.imageFilter(msg);
        }
      };
      module.openCamera(param, resultCallback);
    },
    otherCameraPlus() {
      let that = this;
      var ox = api.require("oxWxRecorder");
      ox.getPermission(function (ret) {
        var code = ret.code;
        if (code == 1) {
          ox.open(
            {
              fixedOn: api.frameName,
              rect: { x: 0, y: 0, w: w, h: h },
              fixed: true,
              type: 2, //0拍照录像 1 录像 2 拍照
            },
            function (ret1) {
              var code1 = ret1.code;
              if (code1 == 0) {
                //关闭事件
              } else if (code1 == 2) {
                //返回图片路径path
                that.imageFilter(ret1.path);
              } else if (code1 == -1) {
                //错误信息
                alert(ret1.text);
              }
            }
          );
        }
      });
    },
    iosCamera() {
      let that = this;
      let zySmallVideo = api.require("zySmallVideo");
      zySmallVideo.openNew(
        {
          rect: {
            //模块 附于一个frame之上
            x: 0,
            y: 0,
            w: api.frameWidth,
            h: api.frameHeight,
          },
          fixedOn: api.frameName,
          fixed: true,
          videoInfo: {
            setOutputFormat: 2, //录制格式 默认2 mp4  0（DEFAULT） 1（THREE_GPP） 2（MPEG_4默认） 3（RAW_AMR） 4（AMR_WB） 5（AAC_ADIF） 6（AAC_ADTS） 7（OUTPUT_FORMAT_RTP_AVP） 8（OUTPUT_FORMAT_MPEG2TS） 9（WEBM）
            setVideoEncoder: 2, //编码格式 默认2 h264 0（DEFAULT） 1（H263） 2（H264默认） 3（MPEG_4_SP） 4（VP8） 5（HEVC）
            setAudioEncoder: 3, //音频格式应该是 默认3 aac  0（DEFAULT） 1（AMR_NB） 2（AMR_WB） 3（AAC默认） 4（HE_AAC） 5（AAC_ELD） 6（VORBIS）
          },
          MaxRecordTime: 60, //最大录制时间 单位秒 默认10
          MinRecordTime: 5, //最短录制时间  单位s
          MinTimeText: "时间不能小于5秒，不能大于60秒", //最短时间提示词
          setFeatures: 1001, //设置拍照和录像   1001只拍照   1002只录像   1003两者都可以  默认1003
          setTip: "", //设置按钮上的提示词   长按拍摄等 默认空
          setBackIcon: "", //自定义返回图标 默认向下键头  支持widget  fs 等路径图片
          setBackShow: 1, //设置返回图标是否显示 1是 0否  默认1
          setCameraIcon: "", //自定义切换摄像头图标  支持widget  fs 等路径图片
          setCameraShow: 1, //右上角切换摄像头是否显示 1是 0否 默认1
          cameraInfo: {
            //摄像头 设置样式
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            margin_l: 0, //距左 默认都是0
            margin_r: 35, //距右
            margin_t: 65, //距上
            margin_b: 0, //距下
          },
          foucsInfo: {
            //点击的对焦框 样式
            color: "#cd0000", //线条颜色 默认16AE16
            width: 4, //线条宽度 默认4
          },
          recordInfo: {
            progress_color: "#cd0000", //进度条颜色 默认16AE16
            outside_color: "#DCDCDC", //外圆背景色 默认DCDCDC
            inside_color: "#FFFFFF", //内圆背景色 默认FFFFFF
          },
          confirmInfo: {
            //确认框参数
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            img: "", //设置自定义图片
          },
          cancelInfo: {
            //取消框参数
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            img: "", //设置自定义图片
          },
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.type == "captureSuccess") {
              that.imageFilter(ret.result);
            }
          }
        }
      );
    },
    //图片压缩
    imageFilter(imgPath) {
      let that = this;
      var imageFilter = api.require("imageFilter");
      var imageCachePath = api.cacheDir; //cache://协议对应的真实目录，字符串类型
      imageFilter.compress(
        {
          img: imgPath,
          quality: 0.5,
          size: "800X600",
          save: {
            album: false,
            imgPath: imageCachePath + "/",
            imgName: "cs.jpg",
          },
        },
        function (ret, err) {
          let imgUrl = imageCachePath + "/cs.jpg";
          that.getFileName("pic", imgUrl);
          //文件删除
          var fs = api.require("fs");
          fs.remove(
            {
              path: imgPath,
            },
            function (ret, err) {
              if (ret.status) {
              } else {
              }
            }
          );
        }
      );
    },
    //获取文件名称
    async getFileName(fType, fUrl) {
      let type = "jpg";
      if (fType === "audio") {
        type = "amr";
      } else if (fType === "video") {
        type = "mp4";
      } else if (fType === "pic") {
        type = "jpg";
      }
      let res = await _httpClient.get(
        _httpClient.getApiPrefix() + "/minio/oss/getFileName?fileType=" + type
      );
      if (res.code === 200) {
        //上传文件
        this.putObj(fType, fUrl, res.fileName);
      }
    },
    //定时器
    timeCycle(fType, fileName) {
      let that = this;
      let cycleNum = 0;
      that.uploadSuccess = false;
      let intervald = setInterval(() => {
        if (
          that &&
          !that._isDestroyed &&
          cycleNum < _httpClient.getUploadCycle() &&
          !that.uploadSuccess
        ) {
          setTimeout(() => {
            if (that && !that._isDestroyed) {
              that.queryFileUpload(fType, fileName);
              cycleNum++;
            }
          }, 0);
        } else {
          //清除定时器
          clearInterval(intervald);
          that.uploadSuccess = true;
          Toast.clear();
          if (cycleNum == _httpClient.getUploadCycle()) {
            alert("上传超时，请重试");
          }
        }
      }, 2000);
    },
    //查询文件是否上传成功
    async queryFileUpload(fType, fileName) {
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "校验保存中...",
      });
      let that = this;
      let res = await _httpClient.get(
        _httpClient.getApiPrefix() + "/minio/oss/" + fileName
      );
      if (res.code === 200) {
        let urls = res.objectURL.split("?");
        if (urls.length > 0) {
          if (fType === "audio") {
            that.form.audioList.push(urls[0]);
          } else if (fType === "video") {
            that.form.videoList.push(urls[0]);
          } else if (fType === "pic") {
            that.form.picList.push(urls[0]);
          } else if (fType === "audio2") {
            that.form.audioList.push(urls[0]);
          }
          Toast("上传成功");
        }
        Toast.clear();
        that.uploadSuccess = true;
      }
    },
    //文件上传
    putObj(fType, fUrl, fileName) {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "上传中...0%",
      });
      api.ajax(
        {
          url:
            _httpClient.getApiPrefix() +
            "/minio/oss/appPutObject?fileName=" +
            fileName,
          //  url: 'http://192.168.2.102:8083' + '/minio/oss/putObject',
          method: "post",
          headers: {
            Authorization: "Bearer " + getToken(),
          },
          report: true,
          data: {
            files: {
              file: fUrl,
            },
          },
        },
        function (ret, err) {
          if (ret) {
            Toast.loading({
              mask: true,
              forbidClick: true,
              duration: 0,
              message: "上传进度...\n" + ret.progress + "%",
            });
            if (ret.body.code === 200) {
              if (api.systemType == "ios") {
                _this.timeCycle(fType, fileName);
                //文件删除
                var fs = api.require("fs");
                fs.remove(
                  {
                    path: fUrl,
                  },
                  function (ret, err) {
                    if (ret.status) {
                    } else {
                    }
                  }
                );
              }
            } else if (ret.progress == 100) {
              _this.timeCycle(fType, fileName);
              //文件删除
              var fs = api.require("fs");
              fs.remove(
                {
                  path: fUrl,
                },
                function (ret, err) {
                  if (ret.status) {
                  } else {
                  }
                }
              );
            }
          } else {
            Toast.clear();
          }
        }
      );
    },
    //保存
    async saveform() {
      let _this = this;
      if (_this.form.planworkdatetime == "") {
        Toast.fail("请选择日期");
        return;
      }
      if (_this.form.workhour == 0) {
        Toast.fail("请输入临时用工工时");
        return;
      }
      if (_this.form.workertype == "") {
        Toast.fail("请选择用工类型");
        return;
      }
      if (
        parseFloat(_this.form.workhour) >
        parseFloat(_this.form.factworksused) * 24
      ) {
        Toast.fail("临时用工数值超出异常");
        return;
      }
      if (parseFloat(_this.form.workhour) < 1.0) {
        Toast.fail("临时用工数值小于异常");
        return;
      }
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "保存中...",
      });
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/app/manhourfact/temporarywork/save",
          {
            body: {
              companyid: _this.form.companyid,
              planworkdatetime: _this.form.planworkdatetime,
              workertype: _this.form.workertype,
              factworksused: _this.form.factworksused,
              pshiftid: _this.form.pshiftid,
              checked: _this.form.checked,
              creator: _this.form.creator,
              workhour: _this.form.workhour,
              picList: _this.form.picList,
            },
          }
        );
        if (res.code === 200) {
          Toast.success(res.msg);
          _this.reset();
        } else {
          Toast.success(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    async delObj(fType, fUrl) {
      this.btnLoading = false;
      let fname = "";
      try {
        if (fUrl != undefined && fUrl != "" && fUrl != null) {
          fname = fUrl.substring(fUrl.lastIndexOf("/") + 1);
        }
        let res = await _httpClient.delete(
          _httpClient.getApiPrefix() + "/minio/oss/" + fname
        );
        if (res.code === 200) {
          let flist = [];
          if (fType === "audio") {
            flist = this.form.audioList;
          } else if (fType === "video") {
            flist = this.form.videoList;
          } else if (fType === "pic") {
            flist = this.form.picList;
          }
          if (flist.length > 0) {
            for (var i = 0; i < flist.length; i++) {
              if (flist[i] == fUrl) {
                flist.splice(i, 1);
              }
            }
          }
          Toast.success(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    close() {
      api.closeWin();
    },
    reset() {
      this.form.picList = [];
      this.form.workertype = null;
      this.form.workhour = null;
    },
  },
};
</script>

<style>
body {
  background-color: white;
}

.radioteam {
  display: flex;
  align-items: center;
  padding-left: 13px;
  margin-top: 10px;
  margin-left: 24px;
  margin-bottom: 10px;
}

.formstyle {
  font-size: 15px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.table-title-class {
  background-color: #304156;
  color: #fff;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.container.dwo {
  display: flex;
  justify-content: center;
  align-items: center;
}

.buttonLeft {
  position: fixed;
  bottom: 8px;
  float: left;
  width: 49%;
}

.buttonRight {
  position: fixed;
  bottom: 8px;
  float: right;
  left: 51%;
  width: 49%;
  background-color: #f22028;
  border-color: #f22028;
}

.textScroll {
  display: inline-block;
  position: fixed;
  top: 4rem;
  bottom: 5rem;
  overflow: scroll;
  right: 0;
  width: 100%;
  z-index: 1;
}

.message {
  font-size: 15px;
  margin-top: 5px;
  margin-left: -10px;
  font-weight: bold;
}

.mg5 {
  margin-right: 5px;
}

.tag_margin {
  margin: 2px 5px;
}

.card_under {
  height: 100%;
  width: 100%;
  margin: auto;
  background: #ffffff;
  border-radius: 25px;
  box-shadow: 0 0px 0px rgba(0, 0, 0, 0.3);
}

.card_icon {
  text-align: center;
  /* position: absolute; */
  height: 8rem;
  width: 80%;
  margin: 12% 10%;
  background: rgba(35, 180, 237, 1);
  border-radius: 25px;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
}

.text {
  font-size: 18px;
  color: #4e4a67;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 600;
}

.text_small {
  font-size: 16px;
  color: red;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 700;
}

.text_scan {
  font-size: 16px;
  color: #4e4a67;
  margin: auto auto auto 20px;
  line-height: 1.5em;
  text-align: justify;
}
</style>
